#include "precompile.h"
#include "base_file.h"
#include "base_util.h"
#include "base_str.h"

_SSL_BEGIN
_SSBASEL_BEGIN

bool file_readbinary_w(const wchar_t *file_path, ssbin &out, size_t extra_size /*= 0*/)
{
	if(file_path == NULL)
		return false;
	out.clear();

	FILE *file = _wfsopen(file_path, L"rb", _SH_DENYWR);
	if(file == NULL)
		return false;

	fseek(file, 0, SEEK_END);
	size_t fsz = ftell(file);
	fseek(file, 0, SEEK_SET);

	SS_ASSERT(extra_size <= 0x0FFFFFFF);

	out.alloc_ptr(fsz + extra_size);

	fsz = fread(out.ptr(), sizeof(unsigned char), fsz, file);
	out.set_size(fsz);
	memset(out.ptr() + fsz, 0, extra_size);

	fclose(file);
	file = NULL;
	return true;
}

void file_path_regular_dir(tstring &path)
{
	if(path.length() == 0)
		return;
	str_replace(path, _T("/"), _T("\\"));
	if(path[path.length()-1] != _T('\\'))
		path += _T("\\");
}

void file_path_regular_file(tstring &path)
{
	if(path.length() == 0)
		return;
	str_replace(path, _T("/"), _T("\\"));
	if(path[path.length()-1] == _T('\\'))
		path = path.substr(0, path.length()-1);
}

bool file_path_is_absolute(tstring &path)
{
	if(path.length() < 2)
		return false;
	if(path[1] == _T(':') || _tcsstr(path.c_str(), _T("\\\\")) == path.c_str())
		return true;
	return false;
}

bool file_path_append(tstring &path, const tstring &file)
{
	tstring file_l = file;
	file_path_regular_file(file_l);
	if(file_path_is_absolute(file_l))
		return false;
	if(file_l.empty())
		return false;
	if(file_l[0] == _T('\\'))
		file_l = file_l.substr(1);
	file_path_regular_dir(path);
	path += file_l;
	return true;
}


_SSBASEL_END
_SSL_END


